<template>
  <div>
    <canvas ref="pieChartCanvas"></canvas>
  </div>
</template>

<script setup lang="ts">
import { defineProps, onMounted, ref, watch, nextTick } from 'vue';
import Chart from 'chart.js/auto';
import type { CircleDataInter } from "@/type/novel/circle";

// 使用 ref 引用 canvas 元素
const pieChartCanvas = ref<HTMLCanvasElement | null>(null);

// 获取传入的 sonValue
const props = defineProps<{
  sonValue: CircleDataInter;
}>();

let chartInstance: Chart | null = null;

// 绘制图表函数
const drawChart = (data: CircleDataInter) => {
  if (pieChartCanvas.value) {
    const ctx = pieChartCanvas.value.getContext('2d');
    if (ctx) {
      // 如果已存在图表实例，销毁它，重新创建
      if (chartInstance) {
        chartInstance.destroy();
      }

      // 创建新的图表实例
      chartInstance = new Chart(ctx, {
        type: 'pie',
        data: data,
        options: {
          responsive: true,
          plugins: {
            title: {
              display: true,
              text: '脑袋成分',
              font: {
                size: 20,
                color: 'black',  // 设置标题的文字颜色
                weight: 'bold',
              },
              position: 'bottom',
              align: 'center',
            },
            legend: {
              position: 'bottom',
            },
            tooltip: {
              callbacks: {
                label: function (tooltipItem) {
                  return tooltipItem.label + ': ' + tooltipItem.raw + '%';
                }
              }
            }
          },
        }
      });
    }
  }
};

// 在组件挂载后绘制图表
onMounted(() => {
  // 等待 Vue 完全渲染后绘制图表
  nextTick(() => {
    drawChart(props.sonValue);
  });
});

// 监听 sonValue 变化，动态更新图表
watch(() => props.sonValue, (newData) => {
  // 等待 Vue 完全渲染后更新图表
  nextTick(() => {
    drawChart(newData);
  });
});
</script>

<style scoped>
canvas {
  max-width: 500px;
  max-height: 500px;
}
</style>
